package netbay;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class TransactionLog {

	public static final String PAY_BANK = "PAYBANK";
	public static final String PAY_TCD = "PAYTCD";
	public static final String TCD_Name = "TCD";
	public static final String JPMC_NAME = "JPMC";

	private int Id;
	private String comment;
	private String status;

	private String tcdAttach;
	private String tcdCtrl;
	private String jpmcAttach;
	private String jpmcCtrl;

	private String converId;
	private String tcdMsgId;
	private String tcdRefMsgId;
	private String jpmcMsgId;
	private String tcdPartyId;
	private String tcdPartyType;
	private String jpmcPartyId;
	private String jpmcPartyType;

	public Integer getId() {
		return Id;
	}

	public void setId(Integer Id) {
		this.Id = Id;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getTcdAttach() {
		return tcdAttach;
	}

	public void setTcdAttach(String tcdAttach) {
		this.tcdAttach = tcdAttach;
	}

	public String getTcdCtrl() {
		return tcdCtrl;
	}

	public void setTcdCtrl(String tcdCtrl) {
		this.tcdCtrl = tcdCtrl;
	}

	public String getJpmcAttach() {
		return jpmcAttach;
	}

	public void setJpmcAttach(String jpmcAttach) {
		this.jpmcAttach = jpmcAttach;
	}

	public String getJpmcCtrl() {
		return jpmcCtrl;
	}

	public void setJpmcCtrl(String jpmcCtrl) {
		this.jpmcCtrl = jpmcCtrl;
	}

	public String getConverId() {
		return converId;
	}

	public void setConverId(String converId) {
		this.converId = converId;
	}

	public String getTcdMsgId() {
		return tcdMsgId;
	}

	public void setTcdMsgId(String tcdMsgId) {
		this.tcdMsgId = tcdMsgId;
	}

	public String getTcdRefMsgId() {
		return tcdRefMsgId;
	}

	public void setTcdRefMsgId(String tcdRefMsgId) {
		this.tcdRefMsgId = tcdRefMsgId;
	}

	public String getJpmcMsgId() {
		return jpmcMsgId;
	}

	public void setJpmcMsgId(String jpmcMsgId) {
		this.jpmcMsgId = jpmcMsgId;
	}

	public String getTcdPartyId() {
		return tcdPartyId;
	}

	public void setTcdPartyId(String tcdPartyId) {
		this.tcdPartyId = tcdPartyId;
	}

	public String getTcdPartyType() {
		return tcdPartyType;
	}

	public void setTcdPartyType(String tcdPartyType) {
		this.tcdPartyType = tcdPartyType;
	}

	public String getJpmcPartyId() {
		return jpmcPartyId;
	}

	public void setJpmcPartyId(String jpmcPartyId) {
		this.jpmcPartyId = jpmcPartyId;
	}

	public String getJpmcPartyType() {
		return jpmcPartyType;
	}

	public void setJpmcPartyType(String jpmcPartyType) {
		this.jpmcPartyType = jpmcPartyType;
	}

	public String toString() {
		return " [" + getId() + "," + getConverId() + "," + getTcdMsgId() + "," + getTcdCtrl()
				+ "," + getTcdAttach() + "," + getJpmcCtrl() + ","
				+ getTcdMsgId() + "," + getJpmcAttach() + "," + getJpmcCtrl()
				+ "] ";
	}

	public String genJpmcCtrlName() {
		String attach = getJpmcAttach();
		String ctrl = attach.substring(0, attach.length() - 3) + "ctrl";
		return ctrl;
	}

	public boolean createJpmcCtrlFile(File ctrlFile) {

		if (!ctrlFile.exists()) {
			try {
				ctrlFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		boolean succeed = false;
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(ctrlFile));

			bw.write("CPA_ID=" + TransactionManager.JPMCcpaId);
			bw.newLine();
			bw.write("SERVICE=" + TransactionManager.JPMCService);
			bw.newLine();
			bw.write("ACTION=" + TransactionManager.JPMCAction);
			bw.newLine();
			bw.write("CONV_ID=" + getConverId());
			bw.newLine();
			bw.write("MSG_ID=" + getJpmcMsgId());
			bw.newLine();
			bw.write("REF_MSG_ID=" + getTcdMsgId());
			bw.newLine();
			bw.write("FROM_PARTY_ID=" + getTcdPartyId());
			bw.newLine();
			bw.write("FROM_PARTY_TYPE=" + getTcdPartyType());
			bw.newLine();
			bw.write("TO_PARTY_ID=" + getJpmcPartyId());
			bw.newLine();
			bw.write("TO_PARTY_TYPE=" + getJpmcPartyType());
			bw.newLine();
			bw.write("TRANSPORT_PROTOCOL="
					+ TransactionManager.JPMCTransportProtocol);
			bw.newLine();
			bw.write("TRANSPORT_ENDPOINT="
					+ TransactionManager.JPMCTransportEndPoint);
			bw.newLine();
			bw.write("PAYLOAD_TYPE=" + TransactionManager.JPMCPayloadType);
			bw.newLine();
			bw.write("PAYLOAD_NAME=" + getJpmcAttach());

			
			succeed = true;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			succeed = false;
		} catch (IOException e) {
			e.printStackTrace();
			succeed = false;
		}
		finally{
			if(bw!=null)
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
		return succeed;
	}

	public void updateJpmcDetail(String attachName) {
		
		
		setJpmcAttach(attachName);
		setJpmcCtrl(genJpmcCtrlName());

		Date now = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

		String msgId = formatter.format(now);
		String Id = String.format("%05d", getId());

		msgId += Id + "@" + SFTPManager.getJPMCIp();

		setJpmcMsgId(msgId);

	}
	
	public boolean setTimeEntry(String timeProperty)
	{
		Integer transactionId = getId();
		
		TransactionTraffic traff = new TransactionTraffic();
		
		traff.setTransactionId(transactionId);
		
		String action = "";
		String process = "";
		
		if(timeProperty.equalsIgnoreCase(TransactionManager.recvTcdStatus))
		{
			action = PAY_TCD;
			process = TransactionManager.recvTcdStatus;
		}
		else if(timeProperty.equalsIgnoreCase(TransactionManager.beginSendJpmcStatus))
		{
			action = PAY_TCD;
			process = TransactionManager.beginSendJpmcStatus;
		}
		else if(timeProperty.equalsIgnoreCase(TransactionManager.finSendJpmcStatus))
		{
			action = PAY_TCD;
			process = TransactionManager.finSendJpmcStatus;
		}
		else if(timeProperty.equalsIgnoreCase(TransactionManager.recvJpmcStatus))
		{
			action = PAY_BANK;
			process = TransactionManager.recvJpmcStatus;
		}
		else if(timeProperty.equalsIgnoreCase(TransactionManager.sendTcdStatus))
		{
			action = PAY_TCD;
			process = TransactionManager.sendTcdStatus;
		}
		else if(timeProperty.equalsIgnoreCase(TransactionManager.resendSFTPStatus))
		{
			action = PAY_TCD;
			process = TransactionManager.resendSFTPStatus;
		}
		else if(timeProperty.equalsIgnoreCase(TransactionManager.redownloadSFTPStatus))
		{
			action = PAY_TCD;
			process = TransactionManager.redownloadSFTPStatus;
		}
		
		traff.setAction(action);
		traff.setProcess(process);
		
		TransactionManager manager = new TransactionManager();
		return manager.insertTraffic(traff);
	}

	public static PreparedStatement convertFindById(Integer id, Connection con)
			throws SQLException {
		
		System.out.println("id is : " + id);
		PreparedStatement st = con
				.prepareStatement("select * from transaction where id = ?");
		st.setInt(1, id);
		
		return st;

	}

	public static PreparedStatement convertFindByConverId(String converId,
			Connection con) throws SQLException {
		PreparedStatement st = con
				.prepareStatement("select * from transaction where conversationid = ?");
		st.setString(1, converId);

		return st;

	}

	public static PreparedStatement convertQueryRecvTcd(Date fromDate,
			Date toDate, Connection con) throws SQLException {
		PreparedStatement st = null;

		if (fromDate != null && toDate != null) {
			st = con.prepareStatement("select * from transaction where recvtcdtime >= ? and recvtcdtime <= ? order by recvtcdtime desc limit 200");
			st.setDate(1, new java.sql.Date(fromDate.getTime()));
			st.setDate(2, new java.sql.Date(toDate.getTime()));
		} else if (fromDate != null && toDate == null) {
			st = con.prepareStatement("select * from transaction where recvtcdtime >= ? order by recvtcdtime desc limit 200");
			st.setDate(1, new java.sql.Date(fromDate.getTime()));
		} else if (fromDate == null && toDate != null) {
			st = con.prepareStatement("select * from transaction where recvtcdtime <= ? order by recvtcdtime desc limit 200");
			st.setDate(1, new java.sql.Date(toDate.getTime()));
		}
		else
		{
			fromDate = new Date();
			Calendar fromCalendar = Calendar.getInstance();
			fromCalendar.setTime(fromDate);
			fromCalendar.add(Calendar.DATE, -1);
			
			fromDate = fromCalendar.getTime();
			
			st = con.prepareStatement("select * from transaction where recvtcdtime >= ? and recvtcdtime <= ? order by recvtcdtime desc limit 200");
			st.setDate(1, new java.sql.Date(fromDate.getTime()));
			st.setDate(2, new java.sql.Date(new Date().getTime()));
			
		}

		return st;
	}

	public static PreparedStatement convertQueryRecvJpmc(Date fromDate,
			Date toDate, Connection con) throws SQLException {
		PreparedStatement st = null;

		if (fromDate != null && toDate != null) {
			st = con.prepareStatement("select * from transaction where recvjpmctime >= ? and recvjpmctime <= ? order by recvjpmctime desc limit 200");
			st.setDate(1, new java.sql.Date(fromDate.getTime()));
			st.setDate(2, new java.sql.Date(toDate.getTime()));
		} else if (fromDate != null && toDate == null) {
			st = con.prepareStatement("select * from transaction where recvjpmctime >= ? order by recvjpmctime desc limit 200");
			st.setDate(1, new java.sql.Date(fromDate.getTime()));
		} else if (fromDate == null && toDate != null) {
			st = con.prepareStatement("select * from transaction where recvjpmctime <= ? order by recvjpmctime desc limit 200");
			st.setDate(1, new java.sql.Date(toDate.getTime()));
		}
		else
		{
			fromDate = new Date();
			Calendar fromCalendar = Calendar.getInstance();
			fromCalendar.setTime(fromDate);
			fromCalendar.add(Calendar.DATE, -1);
			
			fromDate = fromCalendar.getTime();
			
			st = con.prepareStatement("select * from transaction where recvjpmctime >= ? and recvjpmctime <= ? order by recvjpmctime desc limit 200");
			st.setDate(1, new java.sql.Date(fromDate.getTime()));
			st.setDate(2, new java.sql.Date(new Date().getTime()));
			
		}

		return st;
	}

	public static List convertResultsetToDisplay(ResultSet rs)
			throws SQLException {
		List<String[]> displayList = new ArrayList<String[]>();

		while (rs.next()) {

			String[] display = new String[5];
			display[0] = ((String) rs.getObject("conversationid"));
			display[1] = ((String) rs.getObject("status"));
			display[2] = ((String) rs.getObject("tcdmsgid"));
			display[3] = ((String) rs.getObject("jpmcmsgid"));
			display[4] = new Integer(rs.getInt("id")).toString();
			
			displayList.add(display);
			

		}

		return displayList;
	}

	public static String convertInsert(TransactionLog log) throws SQLException {

		String query = "insert into transaction( id, " + "conversationid,"
				+ "tcdmsgid," + "tcdrefmsgid," + "tcdpartyid,"
				+ "tcdpartytype," + "jpmcpartyid," + "jpmcpartytype,"
				+ "tcdattach," + "tcdctrl) " + "values( NULL" + ", \""
				+ log.getConverId() + "\",\"" + log.getTcdMsgId() + "\",\""
				+ log.getTcdRefMsgId() + "\",\"" + log.getTcdPartyId()
				+ "\",\"" + log.getTcdPartyType() + "\",\""
				+ log.getJpmcPartyId() + "\",\"" + log.getJpmcPartyType()
				+ "\",\"" + log.getTcdAttach() + "\",\"" + log.getTcdCtrl()
				+ "\" )";


		return query;
	}

// Obsolete because change the requirement
	
//	public PreparedStatement convertUpdate(String timePropertyName, Connection con) throws SQLException {
//
//		System.out.println(" setting : " + timePropertyName);
//
//		PreparedStatement st = con.prepareStatement("update transaction set "
//				+ timePropertyName + " = ? , status = ? where id = " + getId());
//		
//		st.setTimestamp(1, new Timestamp(new Date().getTime()));
//				
//		String status="";
//		
//		if(timePropertyName.equalsIgnoreCase(TransactionLog.RECV_TCD_TIME))
//		{
//			status = TransactionManager.recvTcdStatus;
//		}
//		else if(timePropertyName.equalsIgnoreCase(TransactionLog.BEGIN_SEND_JPMC_TIME))
//		{
//			status = TransactionManager.beginSendJpmcStatus;
//		}
//		else if(timePropertyName.equalsIgnoreCase(TransactionLog.FIN_SEND_JPMC_TIME))
//		{
//			status = TransactionManager.finSendJpmcStatus;
//		}
//		else if(timePropertyName.equalsIgnoreCase(TransactionLog.RECV_JPMC_TIME))
//		{
//			status = TransactionManager.recvJpmcStatus;
//		}
//		else if(timePropertyName.equalsIgnoreCase(TransactionLog.SEND_TCD_TIME))
//		{
//			status = TransactionManager.sendTcdStatus;
//		}
//		
//		st.setString(2, status);
//
//		return st;
//	}

	public static TransactionLog convertTcdCtrlFile(File ctrlFile) {
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(ctrlFile);
			if (fis != null) {
				prop.load(fis);
			}
		} catch (FileNotFoundException e) {
			System.out.println("error file not found in convert");
			e.printStackTrace();
			return null;
		} catch (IOException e2) {
			System.out.println("error IO not found in convert");
			e2.printStackTrace();
			return null;
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		System.out.println("read succeed");
		
		TransactionLog newLog = new TransactionLog();

		if (prop.getProperty("CONV_ID") != null)
			newLog.setConverId(prop.getProperty("CONV_ID"));

		if (prop.getProperty("MSG_ID") != null)
			newLog.setTcdMsgId(prop.getProperty("MSG_ID"));

		if (prop.getProperty("REF_MSG_ID") != null)
			newLog.setTcdRefMsgId(prop.getProperty("REF_MSG_ID"));

		if (prop.getProperty("FROM_PARTY_ID") != null)
			newLog.setTcdPartyId(prop.getProperty("FROM_PARTY_ID"));

		if (prop.getProperty("FROM_PARTY_TYPE") != null)
			newLog.setTcdPartyType(prop.getProperty("FROM_PARTY_TYPE"));

		if (prop.getProperty("TO_PARTY_ID") != null)
			newLog.setJpmcPartyId(prop.getProperty("TO_PARTY_ID"));

		if (prop.getProperty("TO_PARTY_TYPE") != null)
			newLog.setJpmcPartyType(prop.getProperty("TO_PARTY_TYPE"));

		if (prop.getProperty("PAYLOAD_NAME") != null)
			newLog.setTcdAttach(prop.getProperty("PAYLOAD_NAME"));

		newLog.setTcdCtrl(ctrlFile.getName());
		
		System.out.println("succeed detailing");

		return newLog;
	}

	public static TransactionLog convertResultsetToLog(ResultSet rs) {
		TransactionLog log = null;

		try {
			if (rs.next()) {
				log = new TransactionLog();
				log.setId(rs.getInt("id"));
				log.setComment(rs.getString("comment"));
				log.setStatus(rs.getString("status"));

				log.setTcdAttach(rs.getString("tcdattach"));
				log.setTcdCtrl(rs.getString("tcdctrl"));
				log.setJpmcAttach(rs.getString("jpmcattach"));
				log.setJpmcCtrl(rs.getString("jpmcctrl"));

				log.setConverId(rs.getString("conversationId"));
				log.setTcdMsgId(rs.getString("tcdmsgid"));
				log.setTcdRefMsgId(rs.getString("tcdrefmsgid"));
				log.setJpmcMsgId(rs.getString("jpmcmsgid"));
				log.setTcdPartyId(rs.getString("tcdpartyid"));
				log.setTcdPartyType(rs.getString("tcdpartytype"));
				log.setJpmcPartyId(rs.getString("jpmcpartyid"));
				log.setJpmcPartyType(rs.getString("jpmcpartytype"));

				return log;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;

	}

	public PreparedStatement convertUpdateJPMC(Connection con) {
		
		PreparedStatement st = null;
		try {
			st = con.prepareStatement("update transaction set jpmcattach = ?, jpmcctrl = ?, jpmcmsgid = ? where id = ?");
		
		st.setString(1, getJpmcAttach());
		st.setString(2, getJpmcCtrl());
		st.setString(3, getJpmcMsgId());
		st.setInt(4, getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return st;
	}

}
